<!-- eslint-disable no-console -->
<script lang="ts" setup>
import type { DictApi } from '#/api';
import type { ItemTypeAPI, ItemTypeFormData } from '#/api/mes/md/itemtype';

import { reactive, ref, toRaw } from 'vue';

import { useVbenModal } from '@vben/common-ui';

import { useVbenForm } from '#/adapter/form';
import { DictResp } from '#/api';
import { AddItemType, UpdateItemType } from '#/api/mes/md/itemtype';

const emit = defineEmits(['success']);

// 字典项
const sys_yes_no = reactive<DictApi.SelectOption[]>([]);
const mes_item_product = reactive<DictApi.SelectOption[]>([]);

// 初始化字典数据
DictResp(['sys_yes_no', 'mes_item_product']).then((res) => {
  if (res.sys_yes_no) {
    sys_yes_no.push(...res.sys_yes_no);
  }
  if (res.mes_item_product) {
    mes_item_product.push(...res.mes_item_product);
  }
});

// 用于存储表单数据
const formdata = ref<ItemTypeAPI.Datum>({} as ItemTypeAPI.Datum);

// 表单配置
const [BaseForm, baseFormApi] = useVbenForm({
  showDefaultActions: false,
  commonConfig: {
    componentProps: {
      class: 'w-full',
    },
  },
  layout: 'horizontal',
  handleSubmit: onSubmit,
  schema: [
    {
      component: 'Input',
      rules: 'required',
      fieldName: 'parentTypeName',
      formItemClass: 'w-full ml-[-20px]',
      label: '父分类',
      componentProps: { placeholder: '' },
    },
    {
      component: 'Input',
      rules: 'required',
      formItemClass: ' w-[300px] ml-[-20px]',
      componentProps: {
        placeholder: '',
      },
      fieldName: 'itemTypeName',
      label: '分类名称',
    },
    {
      component: 'InputNumber',
      rules: 'required',
      fieldName: 'orderNum',
      formItemClass: 'w-[300px] ml-[258px] mt-[-60px]',
      label: '显示排序',
      componentProps: {
        min: 0,
        defaultValue: 0,
        controls: true,
        class: 'w-full',
      },
    },
    {
      component: 'RadioGroup',
      rules: 'required',
      componentProps: {
        allowClear: true,
        options: mes_item_product,
      },
      fieldName: 'itemOrProduct',
      label: '物料/产品',
    },
    {
      component: 'RadioGroup',
      formItemClass: 'w-[300px] ml-[258px] mt-[-50px]',
      componentProps: {
        allowClear: true,
        options: sys_yes_no,
        placeholder: '是否启用',
      },
      fieldName: 'enableFlag',
      label: '是否启用',
    },
  ],
  wrapperClass: 'grid-cols-1',
});

// 弹窗配置
const [Modal, modalApi] = useVbenModal({
  closeOnClickModal: false,

  async onConfirm() {
    const { valid } = await baseFormApi.validate();

    if (valid) {
      modalApi.lock();

      const data = formdata.value as ItemTypeFormData;
      try {
        await (formdata.value?.itemTypeId
          ? UpdateItemType(data)
          : AddItemType(data));
        modalApi.close();
        emit('success');
      } finally {
        modalApi.lock(false);
      }
    }
  },

  onOpenChange(isOpen: boolean) {
    if (isOpen) {
      const data = modalApi.getData();

      if (data?.row) {
        formdata.value = { ...toRaw(data.row) };
        baseFormApi.setValues(formdata.value);
      }
    } else {
      formdata.value = {} as ItemTypeAPI.Datum;
      baseFormApi.setValues({});
    }
  },
});

// 备用：手动触发表单提交
function onSubmit(values: Record<string, any>) {
  console.log('[Form Submit]', values);
  modalApi.close();
}
</script>

<template>
  <Modal>
    <BaseForm />
  </Modal>
</template>
